package com.next

import grails.converters.JSON
import grails.transaction.Transactional
import groovy.json.JsonOutput
import groovy.transform.CompileStatic

@Transactional
@CompileStatic
class ContactService
{
    static scope = "singleton"

    def getOpenId(String code)
    {
        // 微信小程序
        // def appid = "wxb51264368f85532b"
        // def secret = "a4b7fa4eefbe8b0c9a6a201a051f3536"

        // 线上
        def appid = "wx6179eaf84943a0ec"
        def secret = "c9f77dc15a909f813b822a7be823115e"

        def openId = ""
        try
        {
            URL url = new URL("https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code")
            def params = "JSCODE=" + URLEncoder.encode(code, 'UTF-8')

            HttpURLConnection connection = (HttpURLConnection) url.openConnection()
            connection.setDoOutput(true)
            connection.setRequestMethod("GET")
            connection.outputStream.withWriter { Writer writer -> writer.write params }
            def response = connection.inputStream.withReader { Reader reader -> reader.text }

            println "微信公众平台响应：" + response

            openId = JSON.parse(response).getAt("openid")
            println "微信公众平台返回OpenID：" + openId

            return openId
        }
        catch (Exception e)
        {
            println e
            log.info "${e}"
            return openId
        }
    }
}
